﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Threading;

namespace MSL.Utility.Threading
{
    /// <summary>
    /// 队列多线程,T 代表处理的单个类型~
    /// 1.处理的是一个确定的列表
    /// 2.提供撤销的功能
    /// 3.提供线程个数修改功能
    /// 4.提供多种事件响应,如单个完成,全部完成的事件
    /// 5.提供完成的百分率
    /// 6.提供终止线程的方式,继续/单线程终止/全部终止
    /// </summary>
    public class ThreadBase<T>
    {
        #region 变量&属性
        /// <summary>
        /// 待处理结果
        /// </summary>
        private class PendingResult
        {
            /// <summary>
            /// 待处理值
            /// </summary>
            public T PendingValue { get; set; }
            /// <summary>
            /// 是否有值
            /// </summary>
            public bool IsHad { get; set; }
        }
        private int _threadCount = 5;
        /// <summary>
        /// 线程列表
        /// </summary>
        List<Thread> _threadList;
        /// <summary>
        /// 完成队列个数
        /// </summary>
        private volatile int _completedQueueCount = 0;
        /// <summary>
        /// 队列总数
        /// </summary>
        private int _queueCount = 0;
        /// <summary>
        /// 全部完成锁
        /// </summary>
        private object _allCompletedLock = new object();
        /// <summary>
        /// 完成的线程数
        /// </summary>
        private int _completedThreadCount = 0;
        /// <summary>
        /// 队列锁
        /// </summary>
        private object _pendingQueueLock = new object();
        private Queue<T> _innerQueue;

        /// <summary>
        /// 线程数
        /// </summary>
        public int ThreadCount
        {
            get { return this._threadCount; }
            set { this._threadCount = value; }
        }
        /// <summary>
        /// 取消=True
        /// </summary>
        public bool Cancel { get; set; }
        #endregion

        #region 事件相关
        /// <summary>
        /// 全部完成事件
        /// </summary>
        public event Action<CompetedEventArgs> AllCompleted;
        /// <summary>
        /// 单个完成事件
        /// </summary>
        public event Action<T, CompetedEventArgs> OneCompleted;
        /// <summary>
        /// 引发全部完成事件
        /// </summary>
        /// <param name="args"></param>
        private void OnAllCompleted(CompetedEventArgs args)
        {
            if (AllCompleted != null)
            {
                try
                {
                    AllCompleted(args);//全部完成事件
                }
                catch { }
            }
        }
        /// <summary>
        /// 引发单个完成事件
        /// </summary>
        /// <param name="pendingValue"></param>
        /// <param name="args"></param>
        private void OnOneCompleted(T pendingValue, CompetedEventArgs args)
        {
            if (OneCompleted != null)
            {
                try
                {
                    OneCompleted(pendingValue, args);
                }
                catch { }

            }
        }
        #endregion

        #region 构造
        public ThreadBase(IEnumerable<T> collection)
        {
            _innerQueue = new Queue<T>(collection);
            this._queueCount = _innerQueue.Count;
        }

        #endregion

        #region 主体
        /// <summary>
        /// 初始化线程
        /// </summary>
        private void InitThread()
        {
            _threadList = new List<Thread>();
            for (int i = 0; i < ThreadCount; i++)
            {
                Thread t = new Thread(new ThreadStart(InnerDoWork));
                _threadList.Add(t);
                t.IsBackground = true;
                t.Start();
            }
        }
        /// <summary>
        /// 开始
        /// </summary>
        public void Start()
        {
            InitThread();
        }
        /// <summary>
        /// 线程工作
        /// </summary>
        private void InnerDoWork()
        {
            try
            {
                Exception doWorkEx = null;
                DoWorkResult doworkResult = DoWorkResult.ContinueThread;
                var t = CurrentPendingQueue;
                while (!this.Cancel && t.IsHad)
                {
                    try
                    {
                        doworkResult = DoWork(t.PendingValue);
                    }
                    catch (Exception ex)
                    {
                        doWorkEx = ex;
                    }
                    _completedQueueCount++;
                    int precent = _completedQueueCount * 100 / _queueCount;
                    OnOneCompleted(t.PendingValue, new CompetedEventArgs() { CompetedPrecent = precent, InnerException = doWorkEx });
                    if (doworkResult == DoWorkResult.AbortAllThread)
                    {
                        this.Cancel = true;
                        break;
                    }
                    else if (doworkResult == DoWorkResult.AbortCurrentThread)
                    {
                        break;
                    }
                    t = CurrentPendingQueue;
                }

                lock (_allCompletedLock)
                {
                    _completedThreadCount++;
                    if (_completedThreadCount == _threadList.Count)
                    {
                        OnAllCompleted(new CompetedEventArgs() { CompetedPrecent = 100 });
                    }
                }
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 子类重写
        /// </summary>
        /// <param name="pendingValue"></param>
        /// <returns></returns>
        protected virtual DoWorkResult DoWork(T pendingValue)
        {
            return DoWorkResult.ContinueThread;
        }
        /// <summary>
        /// 获取当前结果
        /// </summary>
        private PendingResult CurrentPendingQueue
        {
            get
            {
                lock (_pendingQueueLock)
                {
                    PendingResult t = new PendingResult();
                    if (_innerQueue.Count != 0)
                    {
                        t.PendingValue = _innerQueue.Dequeue();
                        t.IsHad = true;
                    }
                    else
                    {
                        t.PendingValue = default(T);
                        t.IsHad = false;
                    }
                    return t;
                }
            }
        }

        #endregion

        #region 枚举
        /// <summary>
        /// dowork结果枚举
        /// </summary>
        public enum DoWorkResult
        {
            /// <summary>
            /// 继续运行，默认
            /// </summary>
            ContinueThread = 0,
            /// <summary>
            /// 终止当前线程
            /// </summary>
            AbortCurrentThread = 1,
            /// <summary>
            /// 终止全部线程
            /// </summary>
            AbortAllThread = 2
        }

        #endregion

        /// <summary>
        /// 异步执行任务
        /// </summary>
        /// <param name="taskAction"></param>
        /// <param name="obj"></param>
        public static void BackgroundWork(Action<object> taskAction, object obj)
        {
            using (System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker())
            {
                bw.RunWorkerCompleted += (s, e) =>
                {
                    //LoadingDlgForm.Close();
                    //LoadingDlgForm.Dispose();
                };

                bw.DoWork += (s, e) =>
                {
                    try
                    {
                        Action<object> a = taskAction;
                        a.Invoke(obj);
                    }
                    catch { }
                };

                bw.RunWorkerAsync();
                //LoadingDlgForm = new WaitDialogForm("正在加载中......", "信息提示");
            }
        }
    }

    #region 使用方法
    /// <summary>
    /// 下载线程对了.
    /// </summary>
    //public class DownLoadQueueThread:ThreadBase<int>
    //{
    //    /// <summary>
    //    /// 
    //    /// </summary>
    //    /// <param name="list">下载的列表ID</param>
    //    public DownLoadQueueThread(IEnumerable<int> list):base(list)
    //    {

    //    }
    //    /// <summary>
    //    /// 每次多线程都到这里来,处理多线程
    //    /// </summary>
    //    /// <param name="pendingValue"列表ID></param>
    //    /// <returns></returns>
    //    protected override DoWorkResult DoWork(int pendingID)
    //    {
    //        try
    //        {
    //            //..........多线程处理....
    //            return DoWorkResult.ContinueThread;//没有异常让线程继续跑..
    //        }
    //        catch (Exception)
    //        {
    //            return DoWorkResult.AbortCurrentThread;//有异常,可以终止当前线程.当然.也可以继续,
    //            //return  DoWorkResult.AbortAllThread; //特殊情况下 ,有异常终止所有的线程...
    //        }
    //        //return base.DoWork(pendingValue);
    //    }
    //}
    #endregion

}
